//
//  UFPageView.m
//  Ufan
//
//  Created by yangqingluo on 15/12/6.
//  Copyright © 2015年 yangqingluo. All rights reserved.
//

#import "UFPageView.h"
#import "UIImageView+EMWebCache.h"

@interface UFPageView()<UIScrollViewDelegate>

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIPageControl *pageControl;

@end

@implementation UFPageView

- (instancetype)initWithArray:(NSArray *)array{
    self = [super init];
    
    if (self) {
        self.imageArray = [array copy];
    }
    
    return self;
}

- (void)didMoveToSuperview{
    [super didMoveToSuperview];
    
    
}

- (void)reloadData{
    self.scrollView.contentSize = CGSizeMake(self.imageArray.count * self.scrollView.bounds.size.width, self.scrollView.bounds.size.height);
    self.scrollView.frame = self.bounds;
    
    self.pageControl.numberOfPages = self.imageArray.count;
    self.pageControl.center = CGPointMake(0.5 * self.bounds.size.width, self.bounds.size.height - 10);
    
    for (NSObject *object in self.imageArray) {
        if ([object isKindOfClass:[UFImage class]]) {
            UFImage *uf_image = (UFImage *)object;
            UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake([self.imageArray indexOfObject:object] * self.scrollView.bounds.size.width, 0, self.scrollView.bounds.size.width, self.scrollView.bounds.size.height)];
            
            [imageView sd_setImageWithURL:[NSURL URLWithString:uf_image.urlPath] placeholderImage:[UIImage imageNamed:@""]];
            [self.scrollView addSubview:imageView];
        }
    }
}

- (NSInteger)indexOfPage{
    return floor((self.scrollView.contentOffset.x - 0.5 * self.scrollView.bounds.size.width) / self.scrollView.bounds.size.width) + 1;
}

#pragma getter
- (UIScrollView *)scrollView{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc]initWithFrame:self.bounds];
        _scrollView.pagingEnabled = YES;
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.delegate = self;
        
        [self addSubview:_scrollView];
    }
    
    return _scrollView;
}

- (UIPageControl *)pageControl{
    if (!_pageControl) {
        _pageControl = [UIPageControl new];
        _pageControl.currentPage = 0;
        
        [self addSubview:_pageControl];
    }
    
    return _pageControl;
}

#pragma UIScrollViewDelegate
/*滚动停止时，触发该函数*/
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {

    
}
/* 触摸屏幕来滚动画面还是其他的方法使得画面滚动，皆触发该函数*/
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if ([scrollView isEqual:self.scrollView]){
        int page = floor((scrollView.contentOffset.x - 0.5 * scrollView.bounds.size.width) / scrollView.bounds.size.width) + 1;
        self.pageControl.currentPage = page;
    }
}

@end
